﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GzipManagerPro.IO.Helpers;

namespace GzipManagerPro.IO
{
    partial class File
    {
        internal override bool WriteTo(System.IO.Stream stream, Archive archive)
        {
            this.Offset = stream.Position;

            ArchiveMessageEventArgs e = new ArchiveMessageEventArgs(1, 0, "{0}", this.Name);
            e.Level = ArchiveMessageType.FileLevel;

            archive.OnArchiveMessage(e);

            System.IO.FileStream fileStream;

            fileStream = new System.IO.FileStream(this.FullPath,
                System.IO.FileMode.Open,
                System.IO.FileAccess.Read,
                System.IO.FileShare.Read);

            e.TotalProgress = fileStream.Length;
            int blockSize = 8192;
            int readBytes;
            byte[] buffer = new byte[blockSize];

            e.Message = string.Format("Compressing file '{0}'...", this.Name);

            string tempFileName = System.IO.Path.GetTempFileName();
            System.IO.FileStream tempStream;

            tempStream = new System.IO.FileStream(tempFileName,
                System.IO.FileMode.OpenOrCreate,
                System.IO.FileAccess.Write,
                System.IO.FileShare.None);

            GZipStream compressor = new GZipStream(tempStream, CompressionMode.Compress);
            while (true)
            {
                readBytes = fileStream.Read(buffer, 0, buffer.Length);

                if (readBytes <= 0)
                    break;

                compressor.Write(buffer, 0, readBytes);
                e.CurrentProgress += readBytes;
                archive.OnArchiveMessage(e);
            }

            
           
            compressor.Close();
            fileStream.Close();
            tempStream.Close();

            tempStream = new System.IO.FileStream(tempFileName,
                System.IO.FileMode.Open,
                System.IO.FileAccess.Read,
                System.IO.FileShare.None);

            e.TotalProgress = this.Length = tempStream.Length;
            e.CurrentProgress = 0;
            e.Message = string.Format("Writing file '{0}'...", this.Name);
            while (true)
            {
                readBytes = tempStream.Read(buffer, 0, buffer.Length);

                if (readBytes <= 0)
                    break;

                stream.Write(buffer, 0, readBytes);
                e.CurrentProgress += readBytes;

                archive.OnArchiveMessage(e);
            }

            tempStream.Close();
            //System.IO.File.Delete(tempFileName);
            
            return true;
        }
    }
}
